package com.yinhd.study.dockingPlatform;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: study
 * @description:
 * @Author: chengl
 * @create: 2022-05-05 16:38
 **/
public class test {
    public static void main(String[] args) {
        try{

            test();

            String response =  MD5.baseMd5(HA1+":"+HD+":"+HA2);
            MD5(MD5(A1):<nonce>:<nc>:<cnonce>:<qop>:MD5(A2))
            String response = MD5.baseMd5(HA1+":"+aa+":"+"00000001"+":"+"248a286a6dda379e"+":"+"auth"+":"+HA2);

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void runble(){
        System.out.println("callable==========");
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //无返回值的业务代码
                System.out.println("55511111");
            }
        });
        thread.start();
    }

    public static String test(){
        try {
            //进入注册，计数器次数+1
            List<String> countList = new ArrayList<String>();
            countList.add("count");
            String ip = "http://10.10.10.45:8888";
            String sendJson = "{\"RegisterObject\":{\"DeviceID\":\"41000000005030312222\"}}";
            boolean successs1 = false;//判断第一次响应是否成功
            Map<String,String> map_FirstReturn = null;
            try {
                //statusCode realm qop nonce
                map_FirstReturn = restConnectForFirst(ip+"/VIID/System/Register", "POST", sendJson);
                String statusCode = map_FirstReturn.get("statusCode");
                //				log.error("第一次请求StatusCode："+statusCode);
                if(statusCode!=null && "401".equals(statusCode)){
                    successs1 = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
                //				log.error("第一次请求注册失败",e);
                return "01";
            }

            boolean successs2 = false;//判断第二次响应是否成功
            if(successs1){//进行第二次请求
                //第一次注册成功 获取响应头中的验证信息
                //				log.error("第一次请求注册成功");
                String Authorization = getResponseCkInfo(map_FirstReturn,countList);
                System.out.println("Authorization="+Authorization);
                //				log.error("Authorization:"+Authorization);
                //				String responseStr2 = RestClient.postByRest("/VIID/System/Register", sendJson, Authorization);
                String responseStr2 = restConnectForSecond(ip+"/VIID/System/Register", "POST", sendJson, Authorization);
                //				log.error("second R:"+responseStr2);
                //向发起方发送成功响应200 OK
                if("201".equals(responseStr2)){
                    successs2 = true;
                }
                System.out.println("Authorization="+Authorization);
                System.out.println("response=="+responseStr2);
                return Authorization;
            }else{
                //第一次请求失败，返回失败信息
                return "01";
            }


        } catch (Exception e) {
            //			log.error("注册信息失败",e);
            return "01";
        }

    }


    public static String testun(){
        try {
            //进入注册，计数器次数+1
            List<String> countList = new ArrayList<String>();
            countList.add("count");
            String ip = "http://10.10.10.45:8088";
            String sendJson = "{\"UnRegisterObject\":{\"DeviceID\":\"12345678905030000001\"}}";
            boolean successs1 = false;//判断第一次响应是否成功
            Map<String,String> map_FirstReturn = null;
            try {
                //statusCode realm qop nonce
                map_FirstReturn = restConnectForFirst(ip+"/VIID/System/UnRegister", "POST", sendJson);
                String statusCode = map_FirstReturn.get("statusCode");
                //				log.error("第一次请求StatusCode："+statusCode);
                if(statusCode!=null && "401".equals(statusCode)){
                    successs1 = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
                //				log.error("第一次请求注册失败",e);
                return "01";
            }

            boolean successs2 = false;//判断第二次响应是否成功
            if(successs1){//进行第二次请求
                //第一次注册成功 获取响应头中的验证信息
                //				log.error("第一次请求注册成功");
                String Authorization = getResponseCkInfo(map_FirstReturn,countList);
                System.out.println("Authorization="+Authorization);
                //				log.error("Authorization:"+Authorization);
                //				String responseStr2 = RestClient.postByRest("/VIID/System/Register", sendJson, Authorization);
                String responseStr2 = restConnectForSecond(ip+"/VIID/System/UnRegister", "POST", sendJson, Authorization);
                //				log.error("second R:"+responseStr2);
                //向发起方发送成功响应200 OK
                if("201".equals(responseStr2)){
                    successs2 = true;
                }
                //				System.out.println("Authorization="+Authorization);
                //				System.out.println("response=="+responseStr2);
                return Authorization;
            }else{
                //第一次请求失败，返回失败信息
                return "01";
            }


        } catch (Exception e) {
            //			log.error("注册信息失败",e);
            return "01";
        }

    }
    private static String getResponseCkInfo(Map<String, String> map_FirstReturn, List<String> countList) {
        //HA1:HD:HA2
        String username =  "admin";
        String pwd = "huawei@123";
        String realm = map_FirstReturn.get("realm");
        String nonce = map_FirstReturn.get("nonce");
        String qop = map_FirstReturn.get("qop");
        String noncecount = getHex(countList.size());
        String cnonce= "248a286a6dda379e";
        String method = "POST";
        String uri = "/VIID/System/UnRegister";

        //		String HA1 = MD5.baseMd5(username+":"+realm+":"+pwd);
        //		String HD = nonce+":::"+qop;
        //		String HA2= MD5.baseMd5(method+":"+uri);

        String HA1 = MD5.baseMd5(username+":"+realm+":"+pwd);
        String HD = nonce+":"+noncecount+":"+cnonce+":"+qop;
        String HA2= MD5.baseMd5(method+":"+uri);
        //		String response =  MD5.baseMd5(HA1+":"+HD+":"+HA2);
        //		MD5(MD5(A1):<nonce>:<nc>:<cnonce>:<qop>:MD5(A2))
        String response = MD5.baseMd5(HA1+":"+nonce+":"+noncecount+":"+cnonce+":"+qop+":"+HA2);
        String Authorization = "Digest ";
        Authorization+="username=\""+username+"\", ";
        Authorization+="realm=\""+realm+"\", ";
        Authorization+="qop=\""+qop+"\", ";
        Authorization+="nonce=\""+nonce+"\", ";
        Authorization+="uri=\""+uri+"\", ";
        Authorization+="cnonce=\""+cnonce+"\", ";
        //		Authorization+="cnonce=\"\", ";
        Authorization+="nc=\""+noncecount+"\", ";
        //		Authorization+="nc=, ";
        Authorization+="response=\""+response+"\"";

        //		Authorization: Digest username="xx",realm="xx",qop="auth",nonce="xx",uri="path",cnonce="xx",nc=00000001,response="xx",opaque="xx"
        //		String Authorization = "{\"username\":\""+username+"\",\"realm\":\""+realm+"\",\"qop\":\""+qop+"\""
        //				+ ",\"uri\":\""+uri+"\",\"cnonce\":\""+cnonce+"\",\"nc\":"+noncecount+",\"response\":\""+response+"\"}";;
        //        Authorization = "Digest username=\"admin\", realm=\"com.stevex.demo\", nonce=\"MTUzMDI0NTMzNTA1NDplOTNjYmMyNzRhNzU1MzNlODFlMWRjZWZmYjEwN2MwNg==\", uri=\"/demo/list\", qop=auth, nc=, cnonce=\"\", response=\"c4d517a96b923ba6b134caaf11c305cb\", opaque=\"\"";
        return Authorization;
    }

    /*
     * 将请求次数转为八位16进制
     */
    private static String getHex(int size) {
        String hex = Integer.toHexString(size);
        if(hex.length()<8){
            int l = 8-hex.length();
            String zero = "";
            for (int i = 0; i < l; i++) {
                zero+="0";
            }
            hex = zero+hex;
        }
        return hex;
    }

    public static Map<String,String> restConnectForFirst(String url,String method,String param) throws IOException {
        Map<String,String> returnMap = new HashMap<String, String>();
        URL restUrl=new URL(url);
        HttpURLConnection conn = (HttpURLConnection) restUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setRequestProperty("Accept-Charset", "UTF-8");//设置请求头
        //设置访问提交模式，表单提交
        conn.setRequestProperty("Content-Type","application/VIID+JSON");
        conn.setConnectTimeout(10000);//连接超时 单位毫秒
        conn.setReadTimeout(5000);//读取超时 单位毫秒
        //连接
        conn.connect();
        //传递参数
        if (param != null) {
            byte[] bypes = param.toString().getBytes("utf-8");
            conn.getOutputStream().write(bypes);
        }
        //传递参数
        Map<String, List<String>> map = conn.getHeaderFields();
        System.out.println("响应码："+conn.getResponseCode());
        returnMap.put("statusCode", conn.getResponseCode()+"");

        for (String key : map.keySet()) {
            System.out.println("响应key："+key);
            if(map.get(key)!=null){
                System.out.println("响应value："+map.get(key).get(0));
                if("WWW-Authenticate".equals(key)){
                    String responStr = map.get(key).get(0).replaceAll("Digest", "").replaceAll(" ", "");
                    if(responStr.indexOf("\r\n")!=-1){
                        System.out.println("有换行");
                    }else{
                        System.out.println("无换行");
                    }
                    String[] arr = responStr.split(",");
                    for (int i = 0; i < arr.length; i++) {
                        if(arr[i].indexOf("realm=")!=-1){
                            String realm = arr[i].replaceAll("realm=", "").replaceAll("\"", "");
                            returnMap.put("realm", realm);
                            System.out.println("realm:"+realm);
                        }else if(arr[i].indexOf("qop=")!=-1){
                            String qop = arr[i].replaceAll("qop=", "").replaceAll("\"", "");
                            returnMap.put("qop", qop);
                            System.out.println("qop:"+qop);
                        }else if(arr[i].indexOf("nonce=")!=-1){
                            String nonce = arr[i].replaceAll("nonce=", "").replaceAll("\"", "");
                            returnMap.put("nonce", nonce);
                            System.out.println("nonce:"+nonce);
                        }
                    }
                }
            }else{
                System.out.println("响应value：null");
            }
        }
        return returnMap;

    }

    /**
     *
     * @param url
     * @param method
     * @param param
     * @throws IOException
     */
    public static String restConnectForSecond(String url,String method,String param,String authentication) throws IOException {
        URL restUrl=new URL(url);
        HttpURLConnection conn = (HttpURLConnection) restUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        //		conn.setRequestProperty("Accept-Charset", "UTF-8");
        //			conn.setRequestProperty("contentType", "UTF-8");
        //设置访问提交模式，表单提交
        //		conn.setRequestProperty("accept","application/json1");
        conn.setRequestProperty("Content-Type","application/json");
        conn.setRequestProperty("Authorization",authentication);
        conn.setConnectTimeout(10000);//连接超时 单位毫秒
        conn.setReadTimeout(5000);//读取超时 单位毫秒
        conn.connect();
        //传递参数
        if (param != null && !"".equals(param)) {
            byte[] bypes = param.toString().getBytes("utf-8");
            conn.getOutputStream().write(bypes);
        }
        InputStream inStream=conn.getInputStream();
        byte[] buffer = new byte[10240];
        int length = 0;
        String strResult = "";
        while ((length = inStream.read(buffer)) != -1) {
            strResult += new String(buffer,0,length,"utf-8");

        }
        System.out.println("strResult:="+strResult);
        //传递参数
        System.out.println("reponse:="+conn.getResponseMessage());
        System.out.println("reponcode:="+conn.getResponseCode());
        return  conn.getResponseCode()+"";

    }
    public static void testPerson(){

    }

}
